
/*
 * Copyright (c) 2020-2021 imlzw@vip.qq.com jweb.cc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.jweb.adai.web.system.dic.controller;

import cc.jweb.adai.web.system.dic.model.SysDic;
import cc.jweb.adai.web.system.log.service.SysLogService;
import cc.jweb.adai.web.system.sys.model.SysLog;
import cc.jweb.boot.common.exception.ParameterValidationException;
import com.jfinal.core.ActionKey;
import com.jfinal.core.NotAction;
import cc.jweb.boot.common.lang.Result;
import cc.jweb.boot.utils.lang.StringUtils;
import cc.jweb.boot.controller.JwebController;
import cc.jweb.boot.db.Db;
import cc.jweb.adai.web.system.generator.utils.GeneratorUtils;
import cc.jweb.boot.security.annotation.Logical;
import cc.jweb.boot.security.annotation.RequiresPermissions;
import io.jboot.web.controller.annotation.RequestMapping;

import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 数据字典
 * 该控制器代码由阿呆代码生成器自动生成
 *
 * @generateDate 2020-12-28 18:18:54
 * @since 1.0
 * @author imlzw
 * @source 阿呆极速开发平台 adai.imlzw.cn
 */
@RequiresPermissions("generator:6:view")
@RequestMapping(value = "/system/dic/table2", viewPath = "/WEB-INF/views/cc/jweb/adai/web/system/dic/gid_6")
public class Table2SysDicController extends JwebController {

    public void index() {
        render("index.html");
    }
    /**
     * 编辑页面
     */
    @RequiresPermissions("generator:6:edit")
    public void editPage() {
        String id = getPara("dic_id");
        SysDic sysDic = null;
        if(id != null) {
            sysDic = SysDic.dao.findById(id);
            if (sysDic == null) {
                sysDic = new SysDic();
            }
        }
        if(sysDic == null) {
            sysDic = new SysDic();
        }
        setAttr("detail", sysDic);
        keepPara();
        render("table2edit.html");
    }

    /**
     * 加载分页列表数据
     */
    @RequiresPermissions("generator:6:list")
    public void list() {
        Map<String, Object> params = getPageParamsPlus();
        params.put("_filters_", GeneratorUtils.parseFilterParams(params));
        Object[] values = getParaValues("values");
        Result result = new Result(false,"未知异常！");
        result.set("code", 400);
        if (StringUtils.isNotBlank(values)){ // formSelects的回显接口
            params.put("_values_",values);
            String valueKey = getPara("valueKey");
            params.put("_valueKey_", valueKey!=null?valueKey:"dic_id");
            result.setListData(Db.find(Db.getSqlPara("gid-6-tno-2-cc.jweb.adai.web.system.dic.sys_dic.queryPageList", params)));
            result.setSuccess(true);
            result.set("code", 0);
        } else {
            result = Db.paginate("gid-6-tno-2-cc.jweb.adai.web.system.dic.sys_dic.queryPageList", "gid-6-tno-2-cc.jweb.adai.web.system.dic.sys_dic.count", params);
            result.set("count", result.get(Result.LIST_TOTAL_KEY));
            result.setSuccess(true);
            result.set("code", 0);
        }
        renderJson(result);
    }

    /**
     * 保存数据字典信息（新增与修改）
     */
    @RequiresPermissions(value = {"generator:6:add","generator:6:edit"}, logical = Logical.OR)
    public void save() {
        SysDic columnModel = getColumnModel(SysDic.class);
        SysDic oldModel = null;
        Object id = columnModel.get("dic_id");
        if (id != null) {
            oldModel = SysDic.dao.findById(id);
        }
        if (oldModel != null) { // 编辑
            fixModel(columnModel);
            verifyModel(columnModel);
            columnModel.update();
        } else { // 新增

            columnModel.set("create_datetime", new Date());
            fixModel(columnModel);
            verifyModel(columnModel);
            columnModel.save();
        }
        SysLogService.service.setSyslog("数据字典", SysLog.STATUS_SUCCESS ," 保存数据字典【" + columnModel.getDicName()+ "】成功！");
        renderJson(new Result(true, "保存数据字典信息成功！"));
    }

    /**
     *  修正模型数据
     *  避免模型非空字段 无数据时，保存或者更新时异常
     */
    @NotAction
    private void fixModel(SysDic columnModel) {
        Set<String> attrs = columnModel._getAttrsEntrySet().stream().map(stringObjectEntry -> stringObjectEntry.getKey()).collect(Collectors.toSet());
        if(attrs.contains("dic_id") && columnModel.get("dic_id")==null){
            // 字段默认值为：NULL
            columnModel.remove("dic_id");
        }

        if(attrs.contains("dic_pid") && columnModel.get("dic_pid")==null){
            // 字段默认值为：0
            columnModel.set("dic_pid", "0");
        }

        if(attrs.contains("dic_code") && columnModel.get("dic_code")==null){
            // 字段默认值为：NULL
            columnModel.remove("dic_code");
        }

        if(attrs.contains("dic_name") && columnModel.get("dic_name")==null){
            // 字段默认值为：NULL
            columnModel.remove("dic_name");
        }

        if(attrs.contains("dic_value") && columnModel.get("dic_value")==null){
            // 字段默认值为：NULL
            columnModel.remove("dic_value");
        }

        if(attrs.contains("is_enable") && columnModel.get("is_enable")==null){
            // 字段默认值为：NULL
            columnModel.remove("is_enable");
        }

        if(attrs.contains("order_no") && columnModel.get("order_no")==null){
            // 字段默认值为：0
            columnModel.set("order_no", "0");
        }

    }

    /**
     *  验证数据
     *  对模型中的字段数据进行校验
     */
    @NotAction
    private void verifyModel(SysDic columnModel) {
        Set<String> attrs = columnModel._getAttrsEntrySet().stream().map(stringObjectEntry -> stringObjectEntry.getKey()).collect(Collectors.toSet());
        if(attrs.contains("dic_code") && columnModel.getDicCode()!=null && columnModel.getDicCode().length() > 64){
            throw new ParameterValidationException("字典代码的长度不能超过64个字符！");
        }
        if(attrs.contains("dic_name") && columnModel.getDicName()!=null && columnModel.getDicName().length() > 128){
            throw new ParameterValidationException("字典名称的长度不能超过128个字符！");
        }
        if(attrs.contains("dic_value") && columnModel.getDicValue()!=null && columnModel.getDicValue().length() > 128){
            throw new ParameterValidationException("字典值的长度不能超过128个字符！");
        }
    }

    /**
     * 删除记录
     */
    @RequiresPermissions("generator:6:del")
    public void delete() {
        String[] ids = getParaValues("ids");
        if (ids == null || ids.length <= 0) {
            renderJson(new Result(true, "删除成功！"));
            return;
        }
        boolean b = true;
        for(String id : ids) {
            b = b & SysDic.dao.deleteById(id);
         }
        SysLogService.service.setSyslog("数据字典", b ? SysLog.STATUS_SUCCESS : SysLog.STATUS_FAILURE, "删除数据字典【id:" + StringUtils.join(ids, ",") + "】" + (b ? "成功" : "失败") + " !");
        renderJson(new Result(b, b ? "删除成功！" : "删除失败！"));
    }

    // ---- 字段关联接口 ----
    /**
     * dic_pid 字段关联表列表接口
     */
    @ActionKey("/system/dic/table2/dic_pid/sql/list")
    public void dicPidSqlList() {
        Map<String, Object> params = getPageParamsPlus();
        params.put("_filters_", GeneratorUtils.parseFilterParams(params));
        Object[] values = getParaValues("values");
        Result result = new Result(false,"未知异常！");
        result.set("code", 400);
        if (StringUtils.isNotBlank(values)){ // formSelects的回显接口
            params.put("dic_ids",values);
            result.setListData(Db.find(Db.getSqlPara("gid-6-tno-2-cc.jweb.adai.web.system.dic.sys_dic.dic_pid_sql_list", params)));
            result.setSuccess(true);
            result.set("code", 0);
        } else {
            result = Db.paginate("gid-6-tno-2-cc.jweb.adai.web.system.dic.sys_dic.dic_pid_sql_list", "gid-6-tno-2-cc.jweb.adai.web.system.dic.sys_dic.dic_pid_sql_count", params);
            result.set("count", result.get(Result.LIST_TOTAL_KEY));
            result.setSuccess(true);
            result.set("code", 0);
        }
        renderJson(result);
    }

}